{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import geemap\n",
    "import ee\n",
    "geemap.set_proxy(port=7890)\n",
    "# ee.Authenticate()\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "from keras.models import load_model\n",
    "Map = geemap.Map()"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "6a8a713f26f4decf"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "model = load_model('test.h5')\n",
    "####################################\n",
    "# filename of the best model\n",
    "####################################\n",
    "config = model.get_config()\n",
    "layers = config['layers']\n",
    "import numpy as np"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "27e906f4d8959d67"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "def cloud_free(image):\n",
    "    \"\"\"\n",
    "        inputs: image\n",
    "        outputs: cloud-free image\n",
    "    \"\"\"\n",
    "    cloud = image.select('QA_PIXEL').rightShift(1).bitwiseAnd(15)\n",
    "    image = image.select('SR_B.').multiply(0.0000275).add(-0.2).addBands(\n",
    "        image.select('QA_PIXEL').rightShift(7).bitwiseAnd(1))\n",
    "    image_freecloud = image.updateMask(cloud.expression('b==0', {'b': cloud}))\n",
    "    return image_freecloud\n",
    "\n",
    "\n",
    "def summer_img(l8, st_year, ed_year, path, row):\n",
    "    \"\"\"\n",
    "        inputs: imagecollection, start year, end year, path, and row\n",
    "        outputs: imagecollection\n",
    "    \"\"\"\n",
    "    landsat = l8.filter(ee.Filter.eq('WRS_PATH', int(path))) \\\n",
    "        .filter(ee.Filter.eq('WRS_ROW', int(row))) \\\n",
    "        .filter(ee.Filter.calendarRange(int(st_year), int(ed_year), 'year')) \\\n",
    "        .filter(ee.Filter.calendarRange(6, 8, 'month')) \\\n",
    "        .sort('CLOUD_COVER')\n",
    "    return landsat\n",
    "\n",
    "\n",
    "def summer_img_bounds(l8, st_year, ed_year, bounds):\n",
    "    \"\"\"\n",
    "        inputs: imagecollection, start year, end year, bound\n",
    "        outputs: imagecollection\n",
    "    \"\"\"\n",
    "    landsat = l8.filter(ee.Filter.calendarRange(int(st_year), int(ed_year), 'year')) \\\n",
    "        .filter(ee.Filter.calendarRange(6, 8, 'month')) \\\n",
    "        .filterBounds(bounds).sort('CLOUD_COVER')\n",
    "    return landsat\n",
    "\n",
    "\n",
    "def features(image):\n",
    "    \"\"\"\n",
    "        inputs: image in gee format\n",
    "        outputs: image with feature bands in gee format\n",
    "    \"\"\"\n",
    "    weights1 = [[0, 0, -1, 0, 0],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [0, 0, 2, 0, 0],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [0, 0, -1, 0, 0]]\n",
    "    weights2 = [[-1, 0, 0, 0, 0],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [0, 0, 2, 0, 0],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [0, 0, 0, 0, -1]]\n",
    "    weights3 = [[0, 0, 0, 0, -1],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [0, 0, 2, 0, 0],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [-1, 0, 0, 0, 0]]\n",
    "    weights4 = [[0, 0, 0, 0, 0],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [-1, 0, 2, 0, -1],\n",
    "                [0, 0, 0, 0, 0],\n",
    "                [0, 0, 0, 0, 0]]\n",
    "    Blue = image.select('SR_B2').rename('B')\n",
    "    Green = image.select('SR_B3').rename('G')\n",
    "    Red = image.select('SR_B4').rename('R')\n",
    "    NIR = image.select('SR_B5').rename('N')\n",
    "    SWIR = image.select('SR_B6').rename('SW')\n",
    "    ndwi = image.normalizedDifference(['SR_B3', 'SR_B6']).rename('mndwi')\n",
    "    smooth1 = ndwi.convolve(ee.Kernel.fixed(weights=ee.List(weights1)))\n",
    "    smooth2 = ndwi.convolve(ee.Kernel.fixed(weights=ee.List(weights2)))\n",
    "    smooth3 = ndwi.convolve(ee.Kernel.fixed(weights=ee.List(weights3)))\n",
    "    smooth4 = ndwi.convolve(ee.Kernel.fixed(weights=ee.List(weights4)))\n",
    "    smooth = ee.Image([smooth1, smooth2, smooth3, smooth4]).reduce(ee.Reducer.max())\n",
    "    smooth = smooth.rename('line')\n",
    "    dem = image.select('elevation').rename('dem')\n",
    "    image = Blue.addBands(Green).addBands(Red).addBands(NIR).addBands(SWIR).addBands(ndwi).addBands(smooth).addBands(\n",
    "        dem)\n",
    "    return image\n",
    "\n",
    "\n",
    "def pixel_based_CNN(image):\n",
    "    \"\"\"\n",
    "        inputs: image\n",
    "        outputs: predicted image\n",
    "    \"\"\"\n",
    "    in_names = [i['inbound_nodes'] for i in layers]\n",
    "    out_names = [i['name'] for i in layers]\n",
    "    new_bandnames = ['B', 'G', 'R', 'N', 'SW', 'mndwi', 'line', 'dem']\n",
    "    results_layers = [image]\n",
    "    for layer in layers[1:]:\n",
    "        if layer['class_name'] == 'Conv2D':\n",
    "            idx = out_names.index(layer['name'])\n",
    "            idx = out_names.index(in_names[idx][0][0][0])\n",
    "            tmp1 = results_layers[idx]\n",
    "            w, b = model.get_layer(layer['config']['name']).get_weights()\n",
    "            bands = [bd['id'] for bd in tmp1.getInfo()['bands']]\n",
    "            kx, ky = layer['config']['kernel_size']\n",
    "            print(w.shape, b.shape)\n",
    "            bef_lon, aft_lon = w.shape[-2:]\n",
    "            \n",
    "            kernel = ee.Kernel.fixed(kx, ky, ee.List(w[:, :, 0, 0].tolist()), -1, -1, False)\n",
    "            tmp = tmp1.select('B').convolve(kernel).add(float(b[0]))\n",
    "            \n",
    "            for j, band_name, bias in zip(range(1, bef_lon), bands[1:], b[1:]):\n",
    "                kernel = ee.Kernel.fixed(kx, ky, ee.List(w[:, :, j, 0].tolist()), -1, -1, False)\n",
    "                tmp = tmp.add(tmp1.select(band_name).convolve(kernel).add(float(bias)))\n",
    "            conv1 = tmp\n",
    "            for i in range(1, aft_lon):\n",
    "                kernel = ee.Kernel.fixed(kx, ky, ee.List(w[:, :, 0, i].tolist()), -1, -1, False)\n",
    "                tmp = tmp1.select(bands[0]).convolve(kernel)\n",
    "                for j, band_name, bias in zip(range(1, bef_lon), bands[1:], b[1:]):\n",
    "                    kernel = ee.Kernel.fixed(kx, ky, ee.List(w[:, :, j, i].tolist()), -1, -1, False)\n",
    "                    tmp = tmp.add(tmp1.select(band_name).convolve(kernel).add(float(bias)))\n",
    "                if layer['config']['activation'] == 'relu':\n",
    "                    tmp = relu(tmp)\n",
    "                else:\n",
    "                    pass\n",
    "                conv1 = ee.Image.cat([conv1, tmp])\n",
    "            results_layers.append(conv1)\n",
    "            print(layer['class_name'], len(results_layers))\n",
    "        elif layer['class_name'] == 'SlicingOpLambda':\n",
    "            idx = out_names.index(layer['name'])\n",
    "            idx = out_names.index(in_names[idx][0][0])\n",
    "            tmp1 = results_layers[idx]\n",
    "            results_layers.append(tmp1)\n",
    "            print(layer['class_name'], len(results_layers),idx)\n",
    "        elif layer['class_name'] == 'Concatenate':\n",
    "            idx = out_names.index(layer['name'])\n",
    "            idx1 = out_names.index(in_names[idx][0][0][0])\n",
    "            idx2 = out_names.index(in_names[idx][0][1][0])\n",
    "            tmp1 = results_layers[idx1]\n",
    "            tmp2 = results_layers[idx2]\n",
    "            results_layers.append(ee.Image.cat([tmp1, tmp2.rename(new_bandnames)]))\n",
    "            print(layer['class_name'], len(results_layers))\n",
    "        else:\n",
    "            print(layer['class_name'], len(results_layers))\n",
    "            print(\"error\")\n",
    "    return results_layers[-1]\n",
    "\n",
    "\n",
    "def relu(image):\n",
    "    return image.gt(0).multiply(image)"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "f795f3d795c81267"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "l8 = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')\n",
    "shp = r'G:\\武汉市数据\\Wuhan_shp\\wuhan.shp'\n",
    "baikal = ee.FeatureCollection(\"projects/ee-cughhx/assets/One_Belt_One_Road/China/Lasa\");"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "30adbfb68d4d53dd"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "#####################################\n",
    "# filename of a boundary shapefile\n",
    "#####################################\n",
    "\n",
    "task = {}\n",
    "for st_year in range(2020, 2021):\n",
    "    ed_year = st_year\n",
    "    DEM_0 = ee.Image('CGIAR/SRTM90_V4').reproject(crs='EPSG:4326', scale=30)\n",
    "    DEM = DEM_0.divide(4000)\n",
    "    imagec = summer_img_bounds(l8, st_year, ed_year, baikal)\n",
    "    image_freecloud = imagec.map(cloud_free).mean().reproject(crs='EPSG:4326', scale=30)\n",
    "    image = image_freecloud.select('SR_B.').addBands(DEM.clip(baikal)).reproject(crs='EPSG:4326', scale=30)\n",
    "    image = image.setDefaultProjection(image.projection())\n",
    "    image = features(image)\n",
    "    result_img = pixel_based_CNN(image)\n",
    "    # 导出到Google Drive\n",
    "    # task[str(st_year)] = ee.batch.Export.image.toDrive(**{\n",
    "    #     'image': result_img.select('B').gt(result_img.select('B_1')),\n",
    "    #     'description': 'baikal_water' + str(st_year),\n",
    "    #     'folder': 'test',\n",
    "    #     ####################################\n",
    "    #     # folder in assets\n",
    "    #     ####################################\n",
    "    #     'scale': 30,\n",
    "    #     'region': baikal.geometry(),\n",
    "    #     'maxPixels': 10000000000\n",
    "    # })\n",
    "    # task[str(st_year)].start()\n",
    "  \n",
    "    # 导出到Asset\n",
    "    task[str(st_year)] = ee.batch.Export.image.toAsset(**{\n",
    "    'image': result_img.select('B').gt(result_img.select('B_1')).clip(baikal),\n",
    "    'description': 'baikal_water' + str(st_year),\n",
    "    'assetId': 'users/hhx/test',\n",
    "    ####################################\n",
    "    # folder in assets\n",
    "    ####################################\n",
    "    'scale': 100,\n",
    "    'region': baikal.geometry(),\n",
    "    'maxPixels': 1e13\n",
    "    })\n",
    "    task[str(st_year)].start()"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "7e4b826f30b7d8c5"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
